package com.baidu.aip;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.media.FaceDetector;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.aip.utils.ImageCompressBase64;
import com.baidu.aip.utils.ImageUtil;

import demo.face.aip.baidu.com.facesdk.R;


/**
 * @author kzcai
 * @packageName com.daai.manage.activity.face
 * @date 2019-12-25
 */
public class RegisterFaceActivity extends Activity {

    private static final String TAG = "RegisterFaceActivity";
    // Intent data.
    private String mFilePath;
    /**
     * 被处理的图片
     */
    private Bitmap mBitmap = null;
    /**
     * 所需的所有权限信息
     */
    private static String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };
    private ImageView mIvShow;
    private FaceDetector mFaceDetector;
    private FaceDetector.Face[] mFaces = new FaceDetector.Face[5];
    private float mEyesDistance;

    private PointF pointF;
    private RectF rectF;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_register_face);
        initView();
        if (!getIntentData(getIntent().getExtras())) {
            this.finish();
        }
        mBitmap = ImageUtil.decodeImage(mFilePath);
        detectFace();
    }

    private void initView() {
        mIvShow = findViewById(R.id.iv_show);
    }




    public void detectFace() {
        if (mBitmap == null) {
            showToast("找不到图片文件");
            finish();
        }
//        Bitmap bitmap = ArcSoftImageUtil.getAlignedBitmap(mBitmap, true);
        int mImageWidth = mBitmap.getWidth();
        int mImageHeight = mBitmap.getHeight();

        mFaceDetector = new FaceDetector(mImageWidth, mImageHeight, 5);
        int num = mFaceDetector.findFaces(mBitmap, mFaces);
//        Log.d(TAG, "detectFace: " + num + "");
        if (num > 0) {
            Bitmap bitmapForDraw = mBitmap.copy(Bitmap.Config.RGB_565, true);
            Canvas canvas = new Canvas(bitmapForDraw);
            Paint paint = new Paint();
            for (int i = 0; i < num; i++) {
                FaceDetector.Face face = mFaces[i];
                pointF = new PointF();
                face.getMidPoint(pointF);
                mEyesDistance = face.eyesDistance();
                paint.setAntiAlias(true);
                paint.setStrokeWidth(5);
                paint.setColor(Color.RED);
                paint.setStyle(Paint.Style.STROKE);
                rectF = new RectF((int) (pointF.x - mEyesDistance*1.1),
                        (int) (pointF.y - mEyesDistance*2/3),
                        (int) (pointF.x + mEyesDistance*1.1),
                        (int) (pointF.y + mEyesDistance * 3 / 2));
                canvas.drawRect(
                        rectF,
                        paint);

                if(mEyesDistance>20){
                    break;
                }
            }
            mIvShow.setImageBitmap(bitmapForDraw);
//            if (mEyesDistance/mBitmap.getWidth()<0.2){
//                showToast("检测到的人脸过小，请靠近拍摄");
//                finish();
//            } else
                if (mEyesDistance/mBitmap.getWidth()>0.5){
                showToast("检测到的人脸过大");
                finish();
            }else {
                int x = (int) (pointF.x - mEyesDistance*2<0?0:pointF.x - mEyesDistance*2);
                int y = (int) (pointF.y - mEyesDistance*2<0?0:pointF.y - mEyesDistance*2);
//                if (x+mEyesDistance*2*2>mBitmap.getWidth()){
//                    showToast("脸部拍摄不全");
//                    finish();
//                    return;
//                }
//                if (y+mEyesDistance*2*2>mBitmap.getHeight()){
//                    showToast("脸部拍摄不全");
//                    finish();
//                    return;
//                }
                Bitmap faceBitmap =  Bitmap.createBitmap(mBitmap,
                        x,
                        y,
                        Math.min((int) (mEyesDistance*2*2),mBitmap.getWidth()-x),
                        Math.min((int) (mEyesDistance*2*2),Math.min(mBitmap.getWidth()-x,mBitmap.getHeight()-y)));
                final String base64 = ImageCompressBase64.INSTANCE.compressToBase64(faceBitmap);
                final byte[] data = ImageCompressBase64.INSTANCE.compressToByteArr(faceBitmap);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.putExtra("imagePath", mFilePath);
//                        intent.putExtra("base64Str",base64);
                        intent.putExtra("data",data);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                },500);
            }

//            if (num==1){

//            }else {
//                showToast("检测到多张人脸，请重新拍摄");
//                finish();
//            }
        } else {
            showToast("未检测到人脸，请重新拍摄");
            finish();
        }
    }

    /**
     * @param bundle
     * @note bundle data :
     * String imagePath
     */
    private boolean getIntentData(Bundle bundle) {
        try {
            mFilePath = bundle.getString("imagePath");
            if (mFilePath == null || mFilePath.isEmpty()) {
                return false;
            }
            Log.i(TAG, "getIntentData:" + mFilePath);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void showToast(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

}
